/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.common.util;

import java.io.Serializable;

/**
 * A simple object that holds onto a pair of object references, first and
 * second.
 * Created by lvyh on 2018/4/25.
 */
final public class Pair<FIRST, SECOND> implements Serializable {
    public final FIRST first;
    public final SECOND second;

    public Pair(FIRST first, SECOND second) {
        this.first = first;
        this.second = second;
    }

    private static boolean equal(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }

    /**
     * 通过值创建值对
     *
     * @param f 第一个值
     * @param s 第二个值
     * @return 值对
     */
    public static <FIRST, SECOND> Pair<FIRST, SECOND> build(FIRST f, SECOND s) {
        return new Pair<FIRST, SECOND>(f, s);
    }

    public static <FIRST, SECOND> Pair<FIRST, SECOND> makePair(FIRST f, SECOND s) {
        return build(f, s);
    }

    @Override
    public int hashCode() {
        return 17 * ((first != null) ? first.hashCode() : 0) + 17 * ((second != null) ? second.hashCode() : 0);
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (!(o instanceof Pair<?, ?>)) {
            return false;
        }
        Pair<?, ?> that = (Pair<?, ?>) o;
        return equal(this.first, that.first) && equal(this.second, that.second);
    }

    @Override
    public String toString() {
        return String.format("(%s,%s)", first, second);
    }
}
